const db = uniCloud.database();

exports.main = async (event, context) => {
  const { data = {} } = event;
  const { dish_id, uid } = data;

  if (!uid) {
    return {
      code: 401,
      message: '未授权',
      data: null
    };
  }

  if (!dish_id) {
    return {
      code: 400,
      message: '菜品ID不能为空',
      data: null
    };
  }

  try {
    const result = await db.collection('food-favorites')
      .where({
        user_id: uid,
        dish_id: dish_id
      })
      .get();

    const favorite = result.data && result.data.length > 0 ? result.data[0] : null;

    return {
      code: 200,
      message: '成功',
      data: {
        isFavorite: !!favorite,
        favorite_id: favorite?._id || null
      }
    };
  } catch (err) {
    return {
      code: 500,
      message: err.message,
      data: null
    };
  }
};
